package com.rzjm.exercise.module.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.ExcelUtils;
import com.rzjm.exercise.common.utils.OssUtil;
import com.rzjm.exercise.common.utils.R;
import com.rzjm.exercise.common.utils.StringUtils;
import com.rzjm.exercise.module.domain.EventsSection;
import com.rzjm.exercise.module.domain.EventsType;
import com.rzjm.exercise.module.service.EventsSectionService;
import com.rzjm.exercise.module.service.EventsTypeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping(value = "/module/eventsSection",produces ="application/json;charset=UTF-8")
public class EventsSectionController extends BaseController {
    @Resource
    private EventsSectionService eventsSectionService;
    @Resource
    private EventsTypeService eventsTypeService;

    @Log("查询隐患项页面")
    @GetMapping("")
    @RequiresPermissions("module:eventsSection:eventsSection")
    String eventsSection(Model model) {
        return "module/eventsSection/list";
    }


    @Log("查询隐患项页面")
    @ResponseBody
    @GetMapping("/list")
    public DataTableLayUI<EventsSection> list(DataTableLayUI<EventsSection> condition) {
        return eventsSectionService.getListPage(condition);
    }


    @Log("新增隐患项页面")
    @GetMapping("/add")
    @RequiresPermissions("module:eventsSection:add")
    String add(Model model) {
        QueryWrapper<EventsType> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<EventsType> typeList = eventsTypeService.list(wrapper);
        model.addAttribute("typeList", typeList);
        EventsSection eventsSection = new EventsSection();
        model.addAttribute("eventsSection", eventsSection);
        return "module/eventsSection/detail";
    }

    @Log("编辑隐患项页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:eventsSection:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        QueryWrapper<EventsType> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<EventsType> typeList = eventsTypeService.list(wrapper);

        EventsSection eventsSection = eventsSectionService.findById(id);
        wrapper.clear();
        wrapper.eq("parent_id",eventsSection.getTypeId());
        List<EventsType> typeChildList = eventsTypeService.list(wrapper);
        model.addAttribute("typeList", typeList);
        model.addAttribute("typeChildList", typeChildList);
        model.addAttribute("eventsSection", eventsSection);
        return "module/eventsSection/detail";
    }


    /**
     * 保存
     */
    @Log("新增隐患项")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:eventsSection:add")
    public R save(@Valid EventsSection eventsSection) {
        eventsSection.setCreateTime(new Date());
        eventsSectionService.save(eventsSection);
        return R.ok();
    }

    @Log("批量新增隐患项页面")
    @GetMapping("/goBatchAdd")
    @RequiresPermissions("module:eventsSection:import")
    String goBatchAdd() {
        return "module/eventsSection/upload";
    }

    @RequestMapping(value = "/readExcelBatchAdd", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("module:eventsSection:import")
    Object readExcel(@RequestParam(value = "file", required = false) MultipartFile file) {
        List<EventsSection> list = ExcelUtils.readExcel("", EventsSection.class, file);
        List<EventsType> typeList = eventsTypeService.selectListByColumn("parent_id", 0);
        QueryWrapper<EventsType> wrapper = new QueryWrapper<>();
        wrapper.gt("parent_id", 0);
        List<EventsType> typeChildList = eventsTypeService.list(wrapper);
        Date date = new Date();
        ArrayList<EventsSection> addList = new ArrayList<>();
        for (int i = 0; i <list.size() ; i++) {
            EventsSection eventsSection = list.get(i);
            if (StringUtils.isNotBlank(eventsSection.getContent())) {
                for (int j = 0; j < typeList.size(); j++) {
                    EventsType eventsType = typeList.get(j);
                    if (eventsType.getTypeName().equals(eventsSection.getTypeName())) {
                        eventsSection.setTypeId(eventsType.getId());
                    }
                }
                if (eventsSection.getTypeId() == null) {
                    EventsType eventsType = new EventsType();
                    eventsType.setTypeName(eventsSection.getTypeName());
                    eventsType.setParentId(0);
                    eventsType.setState(1);
                    eventsType.setSort(1);
                    eventsTypeService.save(eventsType);
                    typeList.add(eventsType);
                    eventsSection.setTypeId(eventsType.getId());
                }
                for (int j = 0; j < typeChildList.size(); j++) {
                    EventsType eventsType = typeChildList.get(j);
                    if (eventsType.getTypeName().equals(eventsSection.getTypeChildName()) && eventsType.getParentId() == eventsSection.getTypeId()) {
                        eventsSection.setTypeChildId(eventsType.getId());
                    }
                }
                if (eventsSection.getTypeChildId() == null) {
                    EventsType eventsType = new EventsType();
                    eventsType.setTypeName(eventsSection.getTypeChildName());
                    eventsType.setParentId(eventsSection.getTypeId());
                    eventsType.setState(1);
                    eventsType.setSort(1);
                    eventsTypeService.save(eventsType);
                    typeChildList.add(eventsType);
                    eventsSection.setTypeChildId(eventsType.getId());
                }
                eventsSection.setCreateTime(date);
                eventsSection.setState(1);
                if (StringUtils.isNotBlank(eventsSection.getEventLevelStr())) {
                    if (eventsSection.getEventLevelStr().equals("一般隐患")) {
                        eventsSection.setEventLevel(1);
                    } else if (eventsSection.getEventLevelStr().equals("重大隐患")) {
                        eventsSection.setEventLevel(2);
                    }
                }
                addList.add(eventsSection);
            }
        }
        if (addList.size() > 0) {
            eventsSectionService.saveBatch(addList,20);
        }
        return R.ok();
    }

    /**
     * 修改
     */
    @Log("更新隐患项")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:eventsSection:edit")
    public R update(@Valid EventsSection eventsSection) {
        eventsSectionService.updateById(eventsSection);
        return R.ok();
    }

    /**
     * 删除
     */
    @Log("删除隐患项")
    @PostMapping( "/remove")
    @ResponseBody
    @RequiresPermissions("module:eventsSection:remove")
    public R remove(Integer id) {
        if (eventsSectionService.removeById(id)) {
            return R.ok();
        }
        return R.error();
    }



    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    Object uploadImg(@RequestParam(value="file", required = false) MultipartFile file){
        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String prefix = fileName.substring((fileName.lastIndexOf(".") + 1)).toLowerCase();
            int upload_type = OssUtil.TYPE_ARTICLE_PHOTOS;
            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix) || "gif".equals(prefix)) {
                try {
                    InputStream inputStream = file.getInputStream();
                    if (inputStream != null) {

                        OssUtil.upload(inputStream, fileName, upload_type);
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String prefixPath = OssUtil.getUploadPrefix(upload_type);
            String signUrl = OssUtil.getSignUrl(prefixPath + fileName);
            HashMap<String, Object> map = new HashMap<>();
            map.put("src",signUrl);
            map.put("title",fileName);
            return R.ok(0,map);
        }
        return R.error();
    }
}
